package com.cgydu.service.impl;

import com.cgydu.dao.UserDao;
import com.cgydu.dao.impl.UserDaoImpl;
import com.cgydu.entity.Message;
import com.cgydu.entity.User;
import com.cgydu.service.UserService;
import com.cgydu.utils.*;

import java.sql.SQLException;

/**
 * projectName: day25_store
 * author: CGY
 * time: 2020/8/26 11:24
 * description:用户业务的实现类
 */
public class UserServiceImpl implements UserService {

    @Override
    public Message checkUser(String username) throws SQLException {
        UserDao userDao = new UserDaoImpl();
        Long aLong = userDao.queryUserNameExist(username);
        Message message = new Message();

        if (aLong == 0)
        {
            message.setCode(Constants.MESSAGE_SUCCESS);
        }
        return message;
    }

    @Override
    public int register(User user) throws SQLException {

        //user  账号  密码  邮箱  性别   激活状态默认  用户类别  默认  激活码未给
        //1.完善user对象
        // UUID.randomUUID().toString(); "asdsadas-asdsadasd-asdsa"
        user.setCode(StrUtils.retUUID());

        user.setUpassword(MD5Utils.md5(user.getUpassword()));

        //2.进行数据库操作
        UserDao userdao =new  UserDaoImpl();
        int rows = userdao.insertUser(user);

        //3.发送邮件
        //554
        EmailUtils.sendEmail(user);

        if (rows>0)
        {
            return Constants.MESSAGE_SUCCESS;
        }

        return Constants.MESSAGE_FAIL;
    }

    @Override
    public int activeUser(String code) throws SQLException {


        //1.code转码
        code =  Base64Utils.decode(code);

        //2.用户状态的改变
        UserDao userDao = new UserDaoImpl();


        //3.查询是否已经激活
        long ct =  userDao.queryUserByCode(code);

        if (ct == 0)
        {
            //code没有查到！ 已经激活！
            return Constants.HASED_ACTIVE;
        }

        //code =  1
        //code  = 0
        int rows =  userDao.updateUserCode(code,Constants.ACTIVE_CODE);

        if (rows>0) {

            //code置空
            userDao.updateUserCodeToNull(code);

            return Constants.ACTIVE_SUCCESS;
        }

        return Constants.ACTIVE_FAIL;
    }



    @Override
    public User login(String username, String password) throws SQLException {

        password = MD5Utils.md5(password); //密码加密

        UserDao userDao = new UserDaoImpl();
        User user =  userDao.queryUser(username,password);

        return user;
    }
}
